//
//  HCCommonTool.m
//  HelperCar
//
//  Created by Jentle on 16/7/26.
//  Copyright © 2016年 Jentle. All rights reserved.
//

#import "HCCommonTool.h"
#import <CommonCrypto/CommonDigest.h>

#define HCApplication  [UIApplication sharedApplication]
#define   kPathOfCache     [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"]

#define radianWithAngel(a) ((a)/180.0*M_PI)

@implementation HCCommonTool

#pragma mark 时间格式处理
+ (NSDate *)dateFromString:(NSString *)dateString
           withFormatStyle:(NSString *)formatStyle{
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatStyle];
    [dateformatter setTimeZone:[NSTimeZone defaultTimeZone]];
    NSDate *date = [dateformatter dateFromString:dateString];
    
    return date;
}

+ (NSDate *)getNotificationMatchDate:(NSString *)dateString addingTimeInterval:(NSTimeInterval)timeInterval
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *date = [[dateFormatter dateFromString:dateString] dateByAddingTimeInterval:timeInterval];
    return date;
}

+ (NSDate *)dateFromString:(NSString *)dateTimeStr
{
    //NSLog(@"dateFromString:%@",dateTimeStr);
    NSArray *array  = [dateTimeStr componentsSeparatedByString:@" "];
    NSArray *dateArr = [[array objectAtIndex:0] componentsSeparatedByString:@"-"];
    NSArray *timeArr = [[array objectAtIndex:1] componentsSeparatedByString:@":"];
    struct tm sourcedate;
    bzero((void*)&sourcedate,sizeof(sourcedate));
    sourcedate.tm_sec = ((NSString *)[timeArr objectAtIndex:2]).intValue;
    sourcedate.tm_min = ((NSString *)[timeArr objectAtIndex:1]).intValue;;
    sourcedate.tm_hour = ((NSString *)[timeArr objectAtIndex:0]).intValue;
    sourcedate.tm_mday = ((NSString *)[dateArr objectAtIndex:2]).intValue;;
    sourcedate.tm_mon = ((NSString *)[dateArr objectAtIndex:1]).intValue - 1;
    sourcedate.tm_year = ((NSString *)[dateArr objectAtIndex:0]).intValue - 1900;
    long timeInterval = mktime(&sourcedate);
    //NSLog(@"timeInterval:%ld",timeInterval);
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    //NSLog(@"date:%@",date);
    return date;
}


+ (NSString *)dateStringFromDate:(NSDate *)date
                 withFormatStyle:(NSString *)formatStyle{
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatStyle];
    NSString *dateStr=[dateformatter stringFromDate:date];
    
    return dateStr;
}

+ (NSString *)dateStringDescriptionByTimeOffset:(NSInteger)offset{
    
    NSTimeInterval second = offset*3600*24;
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:second];
    
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comps = [calendar components:NSCalendarUnitYear fromDate:date];
    
    comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
    NSInteger week = [comps weekday];
    
    NSString *weekday = nil;
    switch (week) {
        case 1:
            weekday = @"星期日";
            break;
        case 2:
            weekday = @"星期一";
            break;
        case 3:
            weekday = @"星期二";
            break;
        case 4:
            weekday = @"星期三";
            break;
        case 5:
            weekday = @"星期四";
            break;
        case 6:
            weekday = @"星期五";
            break;
        case 7:
            weekday = @"星期六";
            break;
            
        default:
            weekday = @"星期";
            break;
    }
    
    NSString *dateStr=[HCCommonTool dateStringFromDate:date
                                            withFormatStyle:@"yyyy-MM-dd"];
    
    return [NSString stringWithFormat:@"%@ %@", dateStr, weekday];
    
}




//返回 小时:分钟
+ (NSString *)formatterHHhhDate:(NSString *)dateString{
    if (dateString.length >16) {
        return [dateString substringWithRange:NSMakeRange(11, 5)];
    }else if (dateString.length > 10){
        
        return [dateString substringWithRange:NSMakeRange(8, 2)];
    }
    return @"00:00";
}

+ (NSString *)formatterDateString:(NSString *)dateString
                    fromFormatter:(NSString *)fromeStyle
                      toFormatter:(NSString *)toStyle{
    
    NSTimeInterval time=[dateString doubleValue];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:fromeStyle];
    [dateformatter setTimeZone:[NSTimeZone defaultTimeZone]];
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:time];
    
    dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:toStyle];
    [dateformatter setTimeZone:[NSTimeZone defaultTimeZone]];
    NSString *dateStr=[dateformatter stringFromDate:date];
    
    return dateStr;
    
}

+ (NSString *)getDateStringFromTimestamp:(NSString *)timestampStr{
    
    NSTimeInterval time=[timestampStr doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    return [dateFormatter stringFromDate: detaildate];
    
}

//*月*日
+ (NSString *)formatterMMDDDate:(NSString *)dateSting
{
    if (dateSting.length > 10) {
        return [NSString stringWithFormat:@"%@月%@日", [dateSting substringWithRange:NSMakeRange(5, 2)], [dateSting substringWithRange:NSMakeRange(8, 2)]];
    }
    return @"1月1日";
}

//*月*日 星期
+ (NSString *)formatterMMDDDateWithWeek:(NSString *)dateSting
                           fomaterStyle:(NSString *)fomaterStyle
{
    NSDate *date = [HCCommonTool dateFromString:dateSting
                                     withFormatStyle:fomaterStyle];
    NSString *nowString = [HCCommonTool dateStringFromDate:[NSDate date] withFormatStyle:@"MM-dd"];
    NSString *MMddString = [HCCommonTool dateStringFromDate:date withFormatStyle:@"MM-dd"];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:NSCalendarUnitMonth fromDate:date];
    NSInteger month = [comps month];
    comps = [calendar components:NSCalendarUnitDay fromDate:date];
    NSInteger day = [comps day];
    comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
    NSString *weekday = nil;
    switch ([comps weekday]) {
        case 1:
            weekday = @"星期日";
            break;
        case 2:
            weekday = @"星期一";
            break;
        case 3:
            weekday = @"星期二";
            break;
        case 4:
            weekday = @"星期三";
            break;
        case 5:
            weekday = @"星期四";
            break;
        case 6:
            weekday = @"星期五";
            break;
        case 7:
            weekday = @"星期六";
            break;
            
        default:
            weekday = @"星期";
    }
    
    if ([nowString isEqualToString:MMddString]) {
        return [NSString stringWithFormat:@"今天 %@", weekday];
    }
    
    return [NSString stringWithFormat:@"%@月%@日 %@", @(month), @(day), weekday];
}


+ (NSString *)totalTimeText:(CGFloat)totalTime{
    
    int time = (int)floor(totalTime);
    int hour = time/3600;
    int munites = time %3600 /60;
    int second = time%3600%60;
    
    NSString *totalString;
    if (!hour) {
        totalString = [NSString stringWithFormat:@"%02d:%02d", munites, second];
    } else {
        totalString = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, munites, second];
    }
    return totalString;
}

+ (NSString *)formattermmssDate:(CGFloat)totalTime{
    
    int time = (int)floor(totalTime);
    int munites = time /60;
    int second = time%60;
    
    NSString *totalString;
    totalString = [NSString stringWithFormat:@"%02d\'%02d\"", munites, second];
    return totalString;
}


#pragma mark - Autolayout coculation size

+ (void)setFittingFrameWithView:(UIView *)view{
    CGFloat height = [view systemLayoutSizeFittingSize:UILayoutFittingExpandedSize].height;
    CGRect frame = view.frame;
    
    frame.size.height = height;
    view.frame = frame;
}

#pragma mark -

+ (BOOL)checkAllIsBlankSpace:(NSString *)string{
    NSString *checkString = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (checkString.length > 0) {
        return NO;
    }
    return YES;
}

#pragma mark 图片处理
+ (UIImage *)imageFromColor:(UIColor *)color Width:(int)width Height:(int) height{
    CGRect rect = CGRectMake(0, 0,width,height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (UIImage *)imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

+ (UIColor *)colorWithHexColorString:(NSString *)hexColorString{
    
    return [HCCommonTool colorWithHexColorString:hexColorString alpha:1.0f];
}

+ (UIColor *)colorWithHexColorString:(NSString *)hexColorString alpha:(float)alpha
{
    if ([hexColorString length] <6){//长度不合法
        return [UIColor blackColor];
    }
    NSString *tempString=[hexColorString lowercaseString];
    if ([tempString hasPrefix:@"0x"]){//检查开头是0x
        tempString = [tempString substringFromIndex:2];
    }else if ([tempString hasPrefix:@"#"]){//检查开头是#
        tempString = [tempString substringFromIndex:1];
    }
    if ([tempString length] !=6){
        return [UIColor blackColor];
    }
    //分解三种颜色的值
    NSRange range;
    range.location =0;
    range.length =2;
    NSString *rString = [tempString substringWithRange:range];
    range.location =2;
    NSString *gString = [tempString substringWithRange:range];
    range.location =4;
    NSString *bString = [tempString substringWithRange:range];
    //取三种颜色值
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString]scanHexInt:&r];
    [[NSScanner scannerWithString:gString]scanHexInt:&g];
    [[NSScanner scannerWithString:bString]scanHexInt:&b];
    return [UIColor colorWithRed:((float) r /255.0f)
                           green:((float) g /255.0f)
                            blue:((float) b /255.0f)
                           alpha:alpha];
}



+ (UIImage *)getScreenShot
{
    UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
    UIGraphicsBeginImageContext(screenWindow.frame.size);
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return viewImage;
}

//showOrHidden=yes 显示；showOrHidden=no，隐藏
+ (void)loadingAnimation:(BOOL)showOrHidden{
    
    UIImageView *iv = (UIImageView *)[[UIApplication sharedApplication].keyWindow viewWithTag:6949];
    
    if (showOrHidden && iv == nil) {
        iv = [[UIImageView alloc] init];
        iv.animationImages = @[];
        [[UIApplication sharedApplication].keyWindow addSubview:iv];
        
    }else if(!showOrHidden && iv){
        [iv removeFromSuperview];
    }
    
}

+ (void)appVersionString {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    NSLog(@"Verson : %@", [NSString stringWithFormat:@"%@ build %@", version, build]);
}


+ (void)showLoading{
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    iv.animationImages = @[[UIImage imageNamed:@"Loading001"],
                           [UIImage imageNamed:@"Loading002"],
                           [UIImage imageNamed:@"Loading003"],
                           [UIImage imageNamed:@"Loading004"],
                           [UIImage imageNamed:@"Loading005"],
                           [UIImage imageNamed:@"Loading006"],
                           [UIImage imageNamed:@"Loading007"],
                           [UIImage imageNamed:@"Loading008"],
                           [UIImage imageNamed:@"Loading009"],
                           [UIImage imageNamed:@"Loading010"],
                           [UIImage imageNamed:@"Loading011"],
                           [UIImage imageNamed:@"Loading012"],
                           [UIImage imageNamed:@"Loading013"],
                           [UIImage imageNamed:@"Loading014"],
                           [UIImage imageNamed:@"Loading015"],
                           [UIImage imageNamed:@"Loading016"]];
    [[UIApplication sharedApplication].keyWindow addSubview:iv];
    iv.animationDuration = 1.2;
    iv.tag = 1357896;
    iv.animationRepeatCount = 0;
    [iv startAnimating];
    
}

+ (void)hiddenLoading{
    
    UIImageView *iv = (UIImageView *)[[UIApplication sharedApplication].keyWindow viewWithTag:1357896];
    [iv stopAnimating];
    [iv removeFromSuperview];
    
}

+ (void)heartbeatView:(UIView *)view repeatCount:(NSInteger)repeat maxSize:(CGFloat)fMaxSize durationPerBeat:(CGFloat)fDurationPerBeat
{
    if (view && (fDurationPerBeat > 0.1f))
    {
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        
        CATransform3D scale1 = CATransform3DMakeScale(0.8, 0.8, 1);
        CATransform3D scale2 = CATransform3DMakeScale(fMaxSize, fMaxSize, 1);
        CATransform3D scale3 = CATransform3DMakeScale(fMaxSize - 0.3f, fMaxSize - 0.3f, 1);
        CATransform3D scale4 = CATransform3DMakeScale(1.0, 1.0, 1);
        
        NSArray *frameValues = [NSArray arrayWithObjects:
                                [NSValue valueWithCATransform3D:scale1],
                                [NSValue valueWithCATransform3D:scale2],
                                [NSValue valueWithCATransform3D:scale3],
                                [NSValue valueWithCATransform3D:scale4],
                                nil];
        
        [animation setValues:frameValues];
        
        NSArray *frameTimes = [NSArray arrayWithObjects:
                               [NSNumber numberWithFloat:0.05],
                               [NSNumber numberWithFloat:0.2],
                               [NSNumber numberWithFloat:0.6],
                               [NSNumber numberWithFloat:1.0],
                               nil];
        [animation setKeyTimes:frameTimes];
        
        animation.fillMode = kCAFillModeForwards;
        animation.duration = fDurationPerBeat;
        animation.repeatCount = repeat;
        
        [view.layer addAnimation:animation forKey:@"heartbeatView"];
    }else{}
}

+ (NSData *)dataWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}

+ (UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


+ (void)buttonSetTitleAndImageEges:(UIButton *)button{
    
    CGPoint buttonBoundsCenter = CGPointMake(CGRectGetMidX(button.bounds), CGRectGetMidY(button.bounds));
    
    CGPoint endImageViewCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetMidY(button.imageView.bounds));
    CGPoint endTitleLabelCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetHeight(button.bounds)-CGRectGetMidY(button.titleLabel.bounds));
    
    
    CGPoint startImageViewCenter = button.imageView.center;
    CGPoint startTitleLabelCenter = button.titleLabel.center;
    
    // 设置imageEdgeInsets
    
    CGFloat imageEdgeInsetsTop = endImageViewCenter.y - startImageViewCenter.y;
    CGFloat imageEdgeInsetsLeft = endImageViewCenter.x - startImageViewCenter.x;
    CGFloat imageEdgeInsetsBottom = -imageEdgeInsetsTop;
    CGFloat imageEdgeInsetsRight = -imageEdgeInsetsLeft;
    button.imageEdgeInsets = UIEdgeInsetsMake(imageEdgeInsetsTop, imageEdgeInsetsLeft, imageEdgeInsetsBottom, imageEdgeInsetsRight);
    
    // 设置titleEdgeInsets
    
    CGFloat titleEdgeInsetsTop = endTitleLabelCenter.y-startTitleLabelCenter.y;
    CGFloat titleEdgeInsetsLeft = endTitleLabelCenter.x - startTitleLabelCenter.x;
    CGFloat titleEdgeInsetsBottom = -titleEdgeInsetsTop;
    CGFloat titleEdgeInsetsRight = -titleEdgeInsetsLeft;
    button.titleEdgeInsets = UIEdgeInsetsMake(titleEdgeInsetsTop, titleEdgeInsetsLeft, titleEdgeInsetsBottom, titleEdgeInsetsRight);
    
    
    
    
}


+ (void)bundleLoadDylibWithPath:(NSString *)path
{
    NSError *err = nil;
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if ([bundle loadAndReturnError:&err]) {
        NSLog(@"bundle load framework success.");
    } else {
        NSLog(@"bundle load framework err:%@",err);
    }
}


+ (void)addRightBarButtonItemForSearchInController:(UIViewController *)vc
                                      withSelector:(SEL)selector{
    
    UIImage *sImage = [UIImage imageNamed:@"discover_ic_search_nor"];
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBarButton.frame= CGRectMake(0, 0, sImage.size.width, sImage.size.height);
    rightBarButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightBarButton setImage:[UIImage imageNamed:@"discover_ic_search_nor"] forState:UIControlStateNormal];
    [rightBarButton setImage:[UIImage imageNamed:@"discover_ic_search_press"] forState:UIControlStateHighlighted];
    [rightBarButton addTarget:vc action:selector forControlEvents:UIControlEventTouchUpInside];
    vc.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarButton];
}

+ (NSString *)regularImagePath:(NSString *)path andWithPathComponent:(NSString *)pathComponent
{
    NSString *pathExtension = [path pathExtension];
    return [[[path stringByDeletingPathExtension] stringByAppendingPathComponent:pathComponent] stringByAppendingPathExtension:pathExtension];
}

+(NSString*)getCtime:(char*)arg
{
    char outstr[200];
    time_t t;
    struct tm *tmp;
    
    t = time(NULL);
    tmp = localtime(&t);
    if (tmp == NULL)
    {
        NSLog(@"%@",@"localtime error");
        return @"";
    }
    
    if (strftime(outstr, sizeof(outstr), arg, tmp) == 0)
    {
        
        NSLog(@"%@",@"strftime returned 0");
        return @"";
    }
    return [NSString stringWithFormat:@"%s",outstr];
}

+(NSString*)getUnixStamp
{
    return  [HCCommonTool getCtime:"%s"];
}

+(CGSize)sizeForString:(NSString *)string font:(UIFont *)font size:(CGSize)size
{
    return [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font} context:nil].size;
}

+ (NSString *)md5Hash:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result);
    NSString *md5Result = [NSString stringWithFormat:
                           @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           result[0], result[1], result[2], result[3],
                           result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11],
                           result[12], result[13], result[14], result[15]
                           ];
    return md5Result;
}

#pragma mark - 验证是否为中文

+ (BOOL)isChinese:(NSString *)inputStr{
    NSString *chinse = @"[\u4e00-\u9fa5]*";
    NSPredicate *regextestChinse = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", chinse];
    return [regextestChinse evaluateWithObject:inputStr];
}

#pragma mark 电话号验证

+ (BOOL)isMobileNumber:(NSString *)mobileNum{
    if ([mobileNum hasPrefix:@"1"] && mobileNum.length == 11) {
        return YES;
    }else{
        return NO;
    }
}

/**
 *  设置圆角(宽和高相等才设置圆角)
 */
+ (void)clipToRoundWithView:(UIView *)aView viewSize:(CGSize)aSize{
   
    CGFloat viewWidth = aView.bounds.size.width;
    CGFloat viewHight = aView.bounds.size.height;
    if (viewWidth > 0 && (viewHight == viewWidth)) {
        aView.layer.cornerRadius = aView.bounds.size.width*0.5;
        aView.layer.masksToBounds = YES;
    }else if (aSize.width == aSize.height){
        aView.layer.cornerRadius = aSize.width*0.5;
        aView.layer.masksToBounds = YES;
    }
    
}
//+ (BOOL)isMobileNumber:(NSString *)mobileNum{
//    /**
//     * 手机号码
//     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     * 联通：130,131,132,152,155,156,185,186
//     * 电信：133,1349,153,180,189
//     */
//    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
//    
//    /**
//     10         * 中国移动：China Mobile
//     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//     12         */
//    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
//    
//    /**
//     15         * 中国联通：China Unicom
//     16         * 130,131,132,152,155,156,185,186
//     17         */
//    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
//    
//    /**
//     20         * 中国电信：China Telecom
//     21         * 133,1349,153,180,189,181
//     22         */
//    NSString * CT = @"^1((33|77|70|71|53|81|8[09])[0-9]|349)\\d{7}$";
//    
//    /**
//     25         * 大陆地区固话及小灵通
//     26         * 区号：010,020,021,022,023,024,025,027,028,029
//     27         * 号码：七位或八位
//     28         */
//    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
//    
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    
//    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
//    
//    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
//    
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
//    
//    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
//    
//    
//    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
//        
//        || ([regextestcm evaluateWithObject:mobileNum] == YES)
//        
//        || ([regextestct evaluateWithObject:mobileNum] == YES)
//        
//        || ([regextestcu evaluateWithObject:mobileNum] == YES)
//        
//        || ([regextestphs evaluateWithObject:mobileNum] == YES))
//        
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
//}

+ (BOOL)hasBlank:(NSString *)string{
    NSRange range = [string rangeOfString:@" "];
    return (range.location != NSNotFound) ? YES : NO;
}

+ (BOOL)isPhoneNumber:(NSString *)str
{
    if (str.length == 11 && [str hasPrefix:@"1"]) {
        return YES;
    }
    return NO;
}

#pragma mark NSString 为空(nil)的验证
+ (BOOL)isEmptyOrNull:(NSString *)string{
    if (string == nil) {
        return YES;
    }
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if ([string isEqualToString:@"(null)"]) {
        return YES;
    }
    if ([string isEqualToString:@"null"]) {
        return YES;
    }
    if (string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+ (BOOL)isPassWord:(NSString *)strPassword
{
    NSString *regex = @"^[A_Za-z0-9]{6,30}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    BOOL isMatch = [pred evaluateWithObject:strPassword];
    
    return isMatch;
}

/**
 *  由url生产图片
 *
 *  @param urlString url
 *
 *  @return 图片
 */
+ (UIImage *)getImageFromURL:(NSString *)urlString{
    NSData *aData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    return [UIImage imageWithData:aData];
}

/**
 *  添加删除线
 *
 *  @param content       字符内容
 *  @param aColor        删除线颜色
 *  @param aBeforeLetter 目的字符串前字符
 *  @param aAfterLetter  目的字符串后字符
 *
 *  @return 带有添加删除线的属性字符串
 */
+ (NSMutableAttributedString *)addStrikethroughWithContent:(NSString *)content color:(UIColor *)aColor beforeLetter:(NSString *)aBeforeLetter afterLetter:(NSString *)aAfterLetter{
    
    NSRange beginRange = [content rangeOfString:aBeforeLetter];
    //    NSRange endRange = [content rangeOfString:aAfterLetter];
    NSRange endRange = [content rangeOfString:aAfterLetter options:NSBackwardsSearch];
    
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:content];
    if (beginRange.location == NSNotFound || endRange.location == NSNotFound){
        attribute = nil;
    }else{
        NSRange attributeRange = NSMakeRange(beginRange.location + 1, content.length - beginRange.location - endRange.length - 1);
        [attribute addAttribute:NSStrikethroughStyleAttributeName value:@( NSUnderlineStyleSingle) range:attributeRange];
        [attribute addAttribute:NSStrikethroughColorAttributeName value:aColor range:attributeRange];
        
    }
    return attribute;
}

/**
 *  添加下划线
 *
 *  @param content 目的字符串
 *  @param aColor  删除线颜色
 *
 *  @return 带有添加删除线的属性字符串
 */
+ (NSMutableAttributedString *)addStrikethroughWithContent:(NSString *)content color:(UIColor *)aColor {
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:content];
    
    NSRange attributeRange = NSMakeRange(0, content.length);
    [attribute addAttribute:NSStrikethroughStyleAttributeName value:@( NSUnderlineStyleSingle) range:attributeRange];
    [attribute addAttribute:NSStrikethroughColorAttributeName value:aColor range:attributeRange];
    return attribute;
}

/**
 *  添加富文本
 *
 *  @param originalStr 原始字符串
 *  @param aRange      目标字符串的范围
 *  @param aSize       富文本字体大小
 *  @param aColor      富文本颜色
 *
 *  @return 富文本属性
 */

+ (NSMutableAttributedString *)stringwithOriginalString:(NSString *)originalStr aRange:(NSRange)aRange aFontSize:(CGFloat)aSize aTextColor:(UIColor *)aColor {
    
    if (originalStr == nil) {
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc]initWithString:originalStr];
    [attributeStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:aSize] range:aRange];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:aColor range:aRange];
    return attributeStr;
}

+ (void)setStatusBarDefaultStyle{
    [HCApplication setStatusBarStyle:UIStatusBarStyleDefault];
}

+ (void)setStatusBarLightContentStyle{
    [HCApplication setStatusBarStyle:UIStatusBarStyleLightContent];
}


+ (NSString *)thousandFormatString:(NSString*)string{
    
    double mydoubleValue = [string doubleValue];
    NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    NSString *numberString = [numberFormatter stringFromNumber: [NSNumber numberWithDouble: mydoubleValue]];
    if([numberString rangeOfString:@"."].location != NSNotFound){
        return numberString;
    }else{
        return [NSString stringWithFormat:@"%@.00",numberString];
    }
}

+ (void)archiveObject:(id)object forKey:(NSString *)key{
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:object forKey:key];
    [archiver finishEncoding];
    NSString *path = [kPathOfCache stringByAppendingPathComponent:key];
    [data writeToFile:path atomically:YES];
}


+ (void)removeObjectForKey:(NSString *)key{
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    NSString *path = [kPathOfCache stringByAppendingPathComponent:key];
    [defaultManager removeItemAtPath:path error:nil];
    
}
+ (id)unArchiveObjectForKey:(NSString *)key{
    
    NSString *path = [kPathOfCache stringByAppendingPathComponent:key];
    
    NSData *data = [NSData dataWithContentsOfFile:path];
    if (data == nil) {
        return nil;
    }else{
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        return [unarchiver decodeObjectForKey:key];
    }
    
}

/**
 *  添加scale形变动画
 */
+ (void)addScaleAnimation:(UIView *)view beginTime:(CFTimeInterval)interval{
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animation];
    keyAnimation.keyPath = @"transform.scale";
    keyAnimation.values = @[@(0.8),@(1),@(0.8)];
    keyAnimation.duration = 2.0f;
    keyAnimation.beginTime = interval;
    keyAnimation.repeatCount = MAXFLOAT;
    [view.layer addAnimation:keyAnimation forKey:nil];
    
}

/**
 *  添加opacity渐变动画
 */
+ (void)addFadeAnimation:(UIView *)view beginTime:(CFTimeInterval)interval{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    animation.fromValue = [NSNumber numberWithFloat:1.0f];
    animation.toValue = [NSNumber numberWithFloat:0.5f];
    animation.autoreverses = YES;
    animation.duration = 2.0;
    animation.repeatCount = MAXFLOAT;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.beginTime = interval;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [view.layer addAnimation:animation forKey:nil];
    
}
/**
 *  添加抖动动画
 */
+ (void)addShakeAnimation:(UIView *)view rotation:(CGFloat)rotation duration:(CGFloat)duration{
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animation];
    keyAnimation.keyPath = @"transform.rotation";
    keyAnimation.values = @[@(radianWithAngel(-rotation)),@(radianWithAngel(rotation)),@(radianWithAngel(-rotation))];
    keyAnimation.repeatCount = MAXFLOAT;
    keyAnimation.duration = duration;
    [view.layer addAnimation:keyAnimation forKey:nil];
}

/**
 *  二次确认弹框
 */
+ (void)addSecConfirmAlertWithController:(UIViewController *)viewController title:(NSString *)title message:(NSString *)message confiemAction:(void(^)(UIAlertAction *action))confiemAction{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (confiemAction) {
            confiemAction(action);
        }
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:cancleAction];
    [alert addAction:okAction];
    [viewController presentViewController:alert animated:true completion:nil];
}


+ (instancetype)createViewFromNibName:(NSString *)nibName
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
    return [nib lastObject];
}

+ (instancetype)createViewFromNib
{
    return [self createViewFromNibName:NSStringFromClass(self.class)];
}



@end
